package top.infopub.mgr.common.filter;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.session.UnknownSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.exception.ServiceException;
import top.infopub.mgr.common.cnst.Constants;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.util.StreamRenderUtil;
import top.infopub.model.sys.ErrorLog;
import top.infopub.tdp.util.ErrorLogUtil;
import top.infopub.zookeeper.confclient.ContextUtils;

import com.alibaba.dubbo.rpc.RpcException;


/**
 * 异常filter 重写Springmvc异常处理器
 * @author Awoke
 * @version 2018年10月14日
 * @see ExceptionHandlerFilter
 * @since
 */
public class ExceptionHandlerFilter implements HandlerExceptionResolver {

    private static final Logger log = LoggerFactory.getLogger(ExceptionHandlerFilter.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object handler, Exception ex) {
        // 不入表 
        if (!(ex instanceof UnknownSessionException)) {
            if (!ex.getClass().getName().contains("ClientAbortException")) {
                log.error("system error ", ex);
                // 异常日志入表  controller层
                final ErrorLog log = new ErrorLog();
                log.setSprojectname(ContextUtils.PROJECT_NAME);
                log.setSerrorname(ex.getClass().getName());
                log.setSerrorinfo(ex.getMessage());
                log.setToperateDate(new Date());
                ErrorLogUtil.log(log);
            }
        }
        if ((request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase(
            "XMLHttpRequest"))
            || (request.getContentType() != null && request.getContentType().toLowerCase().indexOf(
                "multipart/form-data".toLowerCase()) > -1)
            || (request.getContentType() != null && request.getContentType().toLowerCase().indexOf(
                "application/x-www-form-urlencoded".toLowerCase()) > -1)) {
            String error = Constants.GLOBAL_EXCEPTION;
            // 如果是ServiceException异常，则直接返回到页面
            if (ex instanceof ServiceException) {
                error = ex.getMessage();
            }
            // 如果是RpcException异常，则直接返回到页面
            else if (ex instanceof RpcException) {
                error = "服务调用异常，请稍后重试~";
            }
            RspVo<?> resVo = ErrorCodeEnum.ERROR_COMMON_SYSTEM.getRspVo(error);
            StreamRenderUtil.render(resVo, response, null);
            return null;
        }
        else {
            return new ModelAndView("error/500");
        }
    }

}
